//
//  ComposeViewController.swift
//  HMWeibo
//
//  Created by wulei on 15/12/16.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    // MARK: - 懒加载照片选择控制器
    private lazy var picturePickerController = PicturePickerCollection()
    
    // MARK: - 懒加载表情键盘
     lazy var emoticonView: EmotionView = EmotionView { [weak self](emoticon) -> () in
        self?.textView.InsertEmoticon(emoticon)

    }
    
    // MARK: - 监听方法
  @objc private func close() {
    textView.resignFirstResponder()
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
   @objc private func sendStatus() {

    // 获取文本内容
    let text = textView.emoticonText
    
    // 发送微博
    
    let image = picturePickerController.pictures.last
    HMNetworkTools.sharedTools.sendStatus(text, image: image) { (result, error) -> () in
        if error != nil {
            print("出错了")
            SVProgressHUD.showErrorWithStatus("您的网络不给力")
            return
        }
//        print(result)
    }
    
    self.close()
    }

    /// 选择图片
    @objc private func selectPicture() {
        print("选择图片")
        
        textView.resignFirstResponder()
        
        // 如果已经更新了约束就不要再执行以下代码
        if picturePickerController.view.frame.height > 0 {
            return
        }
        
        // 修改图片选择控制器的视图约束
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        // 更新 textView 文本视图的约束
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    /// 选择表情
    @objc private func selectEmoticon() {

        textView.resignFirstResponder()

        textView.inputView = textView.inputView == nil ? emoticonView : nil
        textView.becomeFirstResponder()
        
    }
    
    override func loadView() {
        view = UIView()
        setupUI()
    }
    // MARK: - 键盘处理
/// 键盘变化处理
    @objc private func keyboardChanged(n: NSNotification) {
//print(n)
        //  字典中的结构体CGRect 是NSValue -> CGRect
       let rect =  (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 字典中的值是 NSNumber -> doubleValue
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let curver = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y

        
        //更新textView 的Frame
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        // 强制更新视图
        UIView.animateWithDuration(duration) { () -> Void in
            // 设置动画曲线
            /**
            曲线值 = 7
            － 如果之前的动画没有完成，有启动了其他的动画，让动画的图层直接运动到后续动画的目标位置
            － 一旦设置了 `7`，动画时长无效，动画时长统一变成 0.5s
            */
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curver)!)
            self.view.layoutIfNeeded()

        }
    
    
    
    }
    override func viewDidLoad() {
        super.viewDidLoad()
       NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if picturePickerController.view.frame.height == 0 {
            
            textView.becomeFirstResponder()
        }
    }

// MARK: - 懒加载控件
    /// 工具条
    private lazy var toolbar = UIToolbar()
/// 文本视图
    private lazy var textView: UITextView = {
        let tw = UITextView()
        tw.textColor = UIColor.darkGrayColor()
        tw.font = UIFont.systemFontOfSize(18)
        
        // 始终允许垂直滚动
        tw.alwaysBounceVertical = true
        tw.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tw.delegate = self
        return tw
        }()
/// 占位标签
    private lazy var placeHolderLabel = UILabel(title: "分享新鲜事....", fontSize: 18, color: UIColor.lightGrayColor())

}

// MARK: - UITextViewDelegate
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}
// MARK: - 设置界面
private extension ComposeViewController {
    func setupUI() {
        
        // 取消自动调整滚动视图间距
        automaticallyAdjustsScrollViewInsets = false
        
        
        
        view.backgroundColor = UIColor.whiteColor()
        // 设置控件
        prepareNavigationBar()
        prepareToolBar()
        prepareTextView()
        preparePicturePicker()
        
        
    }
    
/// 准备照片选择控制器
    func preparePicturePicker() {
        // 添加视图
        addChildViewController(picturePickerController)
//        view.addSubview(picturePickerController.view)
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
        
        // 设置约束
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
        make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
//            make.height.equalTo(view.snp_height).multipliedBy(0.6)
            make.height.equalTo(0)
            
        }
        
        
        
    }
    
/// 准备文本视图
    func prepareTextView() {
        view.addSubview(textView)
        textView.backgroundColor = UIColor.yellowColor()
        
        // 设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        
//        textView.text = "分享新鲜事...."
        
        // 添加占位标签
        textView.addSubview(placeHolderLabel)
        
        // 设置约束
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
/// 准备工具条
    func prepareToolBar() {
        view.addSubview(toolbar)
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        // 添加 item
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {

            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["actionName"])
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil))
        }
        items.removeLast()
        toolbar.items = items
        
        // 设置约束
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
    }
    
/// 准备导航栏
    func prepareNavigationBar() {
        // 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendStatus")
        
        // 标题视图
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
//        view.backgroundColor = UIColor.redColor()
        navigationItem.titleView = view
        
        // 禁用发布微博按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 添加子控件
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(title: HMUserAccountViewModel.sharedUserAccountViewModel.account?.screen_name ?? "", fontSize: 13, color: UIColor.lightGrayColor())
        
        view.addSubview(titleLabel)
        view.addSubview(nameLabel)
        
        // 设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top)
            make.centerX.equalTo(view.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom)
        }
    }
}